package zjf.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.Cookie;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import zjf.util.OperationUtil;
import zjf.vo.AdvancedUtil;
import zjf.vo.MD5Util;
import zjf.vo.MessageUtil;
import zjf.vo.Sign;
import zjf.vo.WeixinContons;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


public class WeixinAction extends BaseAction {
	private static final Log log = LogFactory
			.getLog(WeixinAction.class);
	public String page;

	public String getPage() {
		return page;
	}
	public void setPage(String page) {
		this.page = page;
	}
	/**
	 * 
	 * 微信众筹订单生成
	 * @return
	 * @throws Exception
	 */
	public String makeWeixinActivity() {
		String ip=getRequest().getRemoteAddr();
		try {
			msg="true";
			String price="";
			String activityId="";
			if(parms!=null){
				if( parms.get("price")!=null&&!"null".equals(parms.get("price"))&&!"".equals(parms.get("price").toString().trim())){
					price= (int)(Double.parseDouble(parms.get("price").toString())*100)+"";
				}else {
					msg="未获取支付金额信息!";
					return SUCCESS;
				}
				if( parms.get("activityId")!=null&&!"null".equals(parms.get("activityId"))){
					activityId= parms.get("activityId");
				}else {
					msg="未获取众筹活动信息!";
					return SUCCESS;
				}
			}

			String openId=getCookieByName(getRequest(),"zjfmd_openId")!=null?getCookieByName(getRequest(),"zjfmd_openId").getValue():"";
//			openId="oEollt47lV--uNeThDZymRkQf2ew";
			JSONObject js = AdvancedUtil.makeParams(WeixinContons.APPID,WeixinContons.BUSINESSNO,WeixinContons.APPKEY,price,openId,ip,WeixinContons.DESCRIPTION_NAME,WeixinContons.ACTIVITY_NOTIFY_URL,activityId);
			String prepay_id = js.getString("prepay_id");
			if( prepay_id==null){
				msg="未获取微信支付订单信息!";
				return SUCCESS;
			}

			Map<String, String> ret=new HashMap<String, String>();
			String timestamp=Sign.create_timestamp();
			String nonceStr=Sign.create_nonce_str().replace("-", "");

			ret.put("weixin_appId",WeixinContons.APPID);
			ret.put("nonceStr", nonceStr);
			ret.put("packageInfo", "prepay_id="+prepay_id);
			ret.put("timestamp", timestamp);

			SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
			parameters.put("appId", WeixinContons.APPID);
			parameters.put("nonceStr",nonceStr);
			parameters.put("package","prepay_id="+prepay_id);
			parameters.put("signType", "MD5");
			parameters.put("timeStamp", timestamp);
			String signString=MD5Util.createSign("UTF-8",parameters,WeixinContons.APPKEY);
			ret.put("signature", signString);

			resultData.put("config", ret);
		} catch (Exception e) {
			e.printStackTrace();
			log.debug("解析命令出错: " + e.getMessage());
			msg="获取微信配置出错!"+e.getMessage();
		}
		return SUCCESS;
	}
	/**
	 * 
	 * 微信祈福订单生成
	 * @return
	 * @throws Exception
	 */
	public String makeWeixinClifford() {
		String ip=getRequest().getRemoteAddr();
		try {
			msg="true";
			String price="";
			String cliffordId="";
			String tag="";
			String message="";
			if(parms!=null){
				if( parms.get("price")!=null&&!"null".equals(parms.get("price"))&&!"".equals(parms.get("price").toString().trim())){
					price= (int)(Double.parseDouble(parms.get("price").toString())*100)+"";
				}else {
					msg="未获取支付金额信息!";
					return SUCCESS;
				}
				if( parms.get("cliffordId")!=null&&!"null".equals(parms.get("cliffordId"))){
					cliffordId= parms.get("cliffordId");
				}else {
					msg="未获取祈福商品信息!";
					return SUCCESS;
				}
				if( parms.get("tag")!=null&&!"null".equals(parms.get("tag"))){
					tag= parms.get("tag");
				}else {
					msg="未获取标签信息!";
					return SUCCESS;
				}
				if( parms.get("message")!=null&&!"null".equals(parms.get("message"))){
					message= parms.get("message");
				}else {
					msg="未获取留言信息!";
					return SUCCESS;
				}
			}

			String openId=getCookieByName(getRequest(),"zjfmd_openId")!=null?getCookieByName(getRequest(),"zjfmd_openId").getValue():"";
//			openId="oEollt47lV--uNeThDZymRkQf2ew";
			JSONObject js = AdvancedUtil.makeParams(WeixinContons.APPID,WeixinContons.BUSINESSNO,WeixinContons.APPKEY,price,openId,ip,WeixinContons.DESCRIPTION_NAME,WeixinContons.CLIFFORD_NOTIFY_URL,cliffordId+","+tag+","+message);
			String prepay_id = js.getString("prepay_id");
			if( prepay_id==null){
				msg="未获取微信支付订单信息!";
				return SUCCESS;
			}

			Map<String, String> ret=new HashMap<String, String>();
			String timestamp=Sign.create_timestamp();
			String nonceStr=Sign.create_nonce_str().replace("-", "");

			ret.put("weixin_appId",WeixinContons.APPID);
			ret.put("nonceStr", nonceStr);
			ret.put("packageInfo", "prepay_id="+prepay_id);
			ret.put("timestamp", timestamp);

			SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
			parameters.put("appId", WeixinContons.APPID);
			parameters.put("nonceStr",nonceStr);
			parameters.put("package","prepay_id="+prepay_id);
			parameters.put("signType", "MD5");
			parameters.put("timeStamp", timestamp);
			String signString=MD5Util.createSign("UTF-8",parameters,WeixinContons.APPKEY);
			ret.put("signature", signString);

			resultData.put("config", ret);
		} catch (Exception e) {
			e.printStackTrace();
			log.debug("解析命令出错: " + e.getMessage());
			msg="获取微信配置出错!"+e.getMessage();
		}
		return SUCCESS;
	}
	/**
	 * 祈福支付回调
	 * @return
	 */
	public String cliffordPay() {
		System.out.println("cliffordPay支付回调");
		String result=WeixinContons.FAIL;
		String msg="未知异常";
		StringBuffer outStr=new StringBuffer();
		outStr.append("<xml>");
		try {
			Map<String, String> requestMap = MessageUtil.parseXml(getRequest());
			String result_code=requestMap.get("result_code");
			String return_code=requestMap.get("return_code");
			String attach=requestMap.get("attach")!=null?requestMap.get("attach").toString():"";
			String[] attachs=attach.split(",");
			String clifford_id="";
			String tag="";
			String message="";
			if(attachs!=null&&attach.length()>0){
				clifford_id=attachs[0];
				tag=attachs[1];
				message=attachs[2];
			}

			String total_fee=requestMap.get("total_fee").toString();
			String openid=requestMap.get("openid").toString();
			String time_end=requestMap.get("time_end").toString();
			String transaction_id=requestMap.get("transaction_id").toString();
			String return_result="";
			String return_msg="";
			return_result=WeixinContons.FAIL;
			if(WeixinContons.SUCCESS.equals(result_code)&&WeixinContons.SUCCESS.equals(return_code)){//支付成功
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("func_name", "saveCliffordRecord");
				map.put("openId", openid);
				map.put("clifford_id", clifford_id);
				
				map.put("money", total_fee);
				map.put("tag", tag);
				map.put("tag_content", message);
				map.put("order_num", transaction_id);
				map.put("time", time_end);
				
				String returnStr=OperationUtil.result(map);
				JSONObject jsonpara = JSONObject.parseObject(returnStr);
			
				if(jsonpara!=null&&jsonpara.size()>0){
					if(jsonpara.getIntValue("result")==0){
						if(jsonpara.getIntValue("result")==0){
							return_result=WeixinContons.SUCCESS;
						}
						return_msg =  jsonpara.getString("errmessage");
					}else {
						return_msg="未获取到符合条件的数据";
					}
				}else {
					return_msg="网络故障";
				} 
			}
			outStr.append("<return_code><![CDATA["+return_result+"]]></return_code>");
			outStr.append("<return_msg><![CDATA["+return_msg+"]]></return_msg>");
		} catch (Exception e) {
			e.printStackTrace();
			outStr.append("<return_code><![CDATA[FAIL]]></return_code>");
			outStr.append("<return_msg><![CDATA["+e.getMessage()+"]]></return_msg>");
		}finally{
			outStr.append("</xml>");
			PrintWriter out;
			try {
				out = getResponse().getWriter();
				out.print(outStr.toString());
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	/**
	 * 众筹支付回调
	 * @return
	 */
	public String activityPay() {
		System.out.println("activityPay支付回调");
		StringBuffer outStr=new StringBuffer();
		outStr.append("<xml>");
		try {
			Map<String, String> requestMap = MessageUtil.parseXml(getRequest());
			String result_code=requestMap.get("result_code");
			String return_code=requestMap.get("return_code");
			String attach=requestMap.get("attach")!=null?requestMap.get("attach").toString():"";
//			String[] attachs=attach.split(",");
			String activityId=attach;
//			String tag="";
//			String message="";
//			if(attachs!=null&&attach.length()>0){
//				clifford_id=attachs[0];
//				tag=attachs[1];
//				message=attachs[2];
//			}

			String total_fee=requestMap.get("total_fee").toString();
			String openid=requestMap.get("openid").toString();
			String time_end=requestMap.get("time_end").toString();
			String transaction_id=requestMap.get("transaction_id").toString();
			String return_result="";
			String return_msg="";
			return_result=WeixinContons.FAIL;
			if(WeixinContons.SUCCESS.equals(result_code)&&WeixinContons.SUCCESS.equals(return_code)){//支付成功
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("func_name", "saveActivityRecord");
				map.put("activity_id", activityId);
				map.put("openId", openid);
				map.put("money",total_fee);
				map.put("order_num", transaction_id);
				map.put("time", time_end);
				String returnStr=OperationUtil.result(map);
				JSONObject jsonpara = JSONObject.parseObject(returnStr);
			
				if(jsonpara!=null&&jsonpara.size()>0){
					if(jsonpara.getIntValue("result")==0){
						if(jsonpara.getIntValue("result")==0){
							return_result=WeixinContons.SUCCESS;
						}
						return_msg =  jsonpara.getString("errmessage");
					}else {
						return_msg="未获取到符合条件的数据";
					}
				}else {
					return_msg="网络故障";
				} 
			}
			outStr.append("<return_code><![CDATA["+return_result+"]]></return_code>");
			outStr.append("<return_msg><![CDATA["+return_msg+"]]></return_msg>");
		} catch (Exception e) {
			e.printStackTrace();
			outStr.append("<return_code><![CDATA[FAIL]]></return_code>");
			outStr.append("<return_msg><![CDATA["+e.getMessage()+"]]></return_msg>");
		}finally{
			outStr.append("</xml>");
			PrintWriter out;
			try {
				out = getResponse().getWriter();
				out.print(outStr.toString());
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	public Map<String, Object> getResultData() {
		return resultData;
	}
	public void setResultData(Map<String, Object> resultData) {
		this.resultData = resultData;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public int getResult() {
		return result;
	}
	public void setResult(int result) {
		this.result = result;
	}
}
